package com.ovopark.firecar.activity

import android.app.AlertDialog
import android.app.Dialog
import android.app.usage.UsageEvents
import android.bluetooth.BluetoothDevice
import android.text.Editable
import android.util.Log
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.widget.*
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.huashi.bluetooth.HSBlueApi
import com.huashi.bluetooth.HsInterface
import com.huashi.bluetooth.IDCardInfo
import com.ovopark.firecar.R
import com.ovopark.firecar.adapter.ArriveAddressAdapter
import com.ovopark.firecar.adapter.BluetoothDeviceAdapter
import com.ovopark.firecar.bean.ArriveAddressBean
import com.ovopark.firecar.bean.ArrivePeopleInforBean
import com.ovopark.firecar.manager.UserCacheManager
import com.ovopark.firecar.presenter.ReadcardPresenter
import com.ovopark.firecar.utils.SharedPreferencesUtils
import com.ovopark.firecar.utils.StringUtils
import com.ovopark.firecar.view.IReadcardView
import java.util.zip.Inflater

class ReadcardActivity : BaseActivity() {
    lateinit var rlReturn: RelativeLayout
    lateinit var ivBluetoothSetting: ImageView
    lateinit var etUsername: EditText
    lateinit var tvUsernameHint: TextView
    lateinit var tvUsernumHint: TextView
    lateinit var etUsernum: EditText
    lateinit var tvNextStep: TextView
    lateinit var bluetoothConnectDialog: AlertDialog
    lateinit var rvBlueTooth: RecyclerView
    lateinit var linearLayoutManager: LinearLayoutManager
    lateinit var bluetoothAdapter: BluetoothDeviceAdapter
    lateinit var filePath: String
    lateinit var diaView: View
    lateinit var tvScanf: TextView
    lateinit var ivReadcard: ImageView
    var readCard: Int = 0
    lateinit var api: HSBlueApi
    var boudDeviceList: MutableList<BluetoothDevice> = ArrayList()
    var isConn: Boolean = false
    lateinit var icInfor: IDCardInfo
    lateinit var tvDeviceConnectState: TextView

    lateinit var rvAddress: RecyclerView
    lateinit var gridLayoutManager: GridLayoutManager
    lateinit var chooseAddressDialog: AlertDialog

    lateinit var tvChooseArrive: TextView
    lateinit var ivDel: ImageView
    lateinit var ivAdd: ImageView
    lateinit var tvNoCardNum: TextView
    lateinit var arriveAddressAdapter: ArriveAddressAdapter
    lateinit var view: View
    lateinit var linearLayoutManagerAddress: LinearLayoutManager
    var followPeople: Int = 0
    lateinit var presenter: ReadcardPresenter
    var addressList: ArrayList<ArriveAddressBean> = ArrayList()
    var arrivePeopleInfor: ArrivePeopleInforBean = ArrivePeopleInforBean()
    lateinit var rlDeviceConnect: RelativeLayout

    lateinit var exitDialog: AlertDialog
    lateinit var tvConfirm: TextView
    lateinit var tvCancel: TextView

    lateinit var confirmDialog: AlertDialog
    lateinit var tvConfirmConnect: TextView
    lateinit var tvConfirmCancel: TextView
    lateinit var tvUsername: TextView
    lateinit var tvIdCard: TextView
    lateinit var tvArriveAddress: TextView

    lateinit var thread: Thread
    var threadState: Boolean = true
    var clickState: Boolean = true
    override fun initView() {
        super.initView()
        setContentView(R.layout.activity_readcard)
        filePath = "/mnt/sdcard/wltlib"
        api = HSBlueApi(this, filePath)
        readCard = api.init()
        rlDeviceConnect = findViewById(R.id.rl_device_connect)
        rlReturn = findViewById(R.id.rl_return)
        ivReadcard = findViewById(R.id.iv_readcard)
        ivBluetoothSetting = findViewById(R.id.iv_bluetooth_setting)
        etUsername = findViewById(R.id.et_username)
        tvUsernameHint = findViewById(R.id.tv_username_hint)
        tvUsernumHint = findViewById(R.id.tv_usernum_hint)
        etUsernum = findViewById(R.id.et_usernum)
        tvNextStep = findViewById(R.id.tv_next_step)
        tvChooseArrive = findViewById(R.id.tv_choose_arrive)
        ivDel = findViewById(R.id.iv_del)
        ivAdd = findViewById(R.id.iv_add)
        tvNoCardNum = findViewById(R.id.tv_no_card_num)
        tvDeviceConnectState = findViewById(R.id.tv_device_connect_state)

        if (!isConn) {
            tvDeviceConnectState.text = "设备未连接"

            tvDeviceConnectState.setTextColor(ContextCompat.getColor(this, R.color.red_f13642))
        } else {
            tvDeviceConnectState.text = "设备已连接"

            tvDeviceConnectState.setTextColor(ContextCompat.getColor(this, R.color.green_6DC753))
        }
        initPresenter()
        rlReturn.setOnClickListener {
            exitDialog.show()
        }
        initDialog()
        initArriveAddressDialog()
        initExitDialog()
        initConfirmInfor()
        ivBluetoothSetting.setOnClickListener {
            bluetoothConnectDialog.show()
        }

        ivReadcard.setOnClickListener {
            if (clickState) {
                threadState = true
                thread = Thread(object : Runnable {
                    override fun run() {
                        var i = 0
                        runOnUiThread {
                            clickState = false
                        }
                        while (threadState) {
                            i++
                            Thread.sleep(1000)
                            if (i >= 3) {
                                runOnUiThread {
                                    threadState = false
                                    clickState = true
                                }
                            }
                            Log.i("threadState", "threadState: " + threadState + "\ti: " + i)
                        }
                    }

                })
                thread.start()

                if (isConn) {
                    loadingDialog.show()
                    initReadCard()

                } else {
                    Toast.makeText(this, "请先连接读卡器", Toast.LENGTH_SHORT).show()
                }
            }else{
                Toast.makeText(this, "正在识别中，请勿连续点击", Toast.LENGTH_SHORT).show()

            }


        }

        tvChooseArrive.setOnClickListener {
            chooseAddressDialog.show()
        }
        tvNoCardNum.text = followPeople.toString()
        ivAdd.setOnClickListener {
            followPeople += 1
            tvNoCardNum.text = followPeople.toString()

        }

        ivDel.setOnClickListener {
            if (followPeople > 0) {
                followPeople -= 1
                tvNoCardNum.text = followPeople.toString()
            } else {
                Toast.makeText(this, "随行人数错误", Toast.LENGTH_SHORT).show()
                tvNoCardNum.text = followPeople.toString()
            }
        }

        tvNextStep.setOnClickListener {
            tvUsername.text = etUsername.text
            tvIdCard.text = etUsernum.text
            tvArriveAddress.text = tvChooseArrive.text
            confirmDialog.show()

        }

    }

    fun initPresenter() {
        presenter = ReadcardPresenter(this, object : IReadcardView {
            override fun getRecordSuccess(arriveList: ArrayList<ArriveAddressBean>?) {
                arriveAddressAdapter.updata(arriveList)
            }

            override fun getRecordFailed(mes: String?) {
                Toast.makeText(this@ReadcardActivity, mes, Toast.LENGTH_SHORT).show()
            }

            override fun addArriveSuccess(mes: String?) {
                loadingDialog.dismiss()
                resertUI()
                confirmDialog.dismiss()
                Toast.makeText(this@ReadcardActivity, mes, Toast.LENGTH_SHORT).show()
            }

            override fun addArriveFailed(mes: String?) {
                loadingDialog.dismiss()
                Toast.makeText(this@ReadcardActivity, mes, Toast.LENGTH_SHORT).show()

            }

        })
    }


    //初始化选择连接的蓝牙
    fun initDialog() {
        diaView = View.inflate(this, R.layout.dialog_bluetooth_device, null)
        var build: AlertDialog.Builder = AlertDialog.Builder(this)
        build.setView(diaView)
        bluetoothConnectDialog = build.create()
        bluetoothConnectDialog.setCanceledOnTouchOutside(true)

        bluetoothAdapter =
            BluetoothDeviceAdapter(this, api, object : BluetoothDeviceAdapter.DeviceCallback {
                override fun connectState(state: Boolean) {
                    isConn = state
                    if (isConn) {
                        bluetoothConnectDialog.dismiss()
                        tvDeviceConnectState.text = "设备已连接"
                        tvDeviceConnectState.setTextColor(
                            ContextCompat.getColor(
                                this@ReadcardActivity,
                                R.color.green_6DC753
                            )
                        )
                    }
                }

            })
        rvBlueTooth = diaView.findViewById(R.id.rv_bluetooth_connect)
        tvScanf = diaView.findViewById(R.id.tv_scanf)
        linearLayoutManager = LinearLayoutManager(this)
        rvBlueTooth.layoutManager = linearLayoutManager
        rvBlueTooth.adapter = bluetoothAdapter
        initBlueTooth()
        api.scanf()
        tvScanf.setOnClickListener {
            api.scanf()
        }
    }

    //初始化蓝牙设备
    fun initBlueTooth() {
        if (readCard == -1) {
            Toast.makeText(this, "初始化失败", Toast.LENGTH_LONG).show()
        }
        api.setmInterface(object : HsInterface {
            override fun reslut2Devices(map: MutableMap<String, MutableList<BluetoothDevice>>?) {
                if (!map?.get("bind").isNullOrEmpty()) {
                    boudDeviceList = map?.get("bind")!!
                    bluetoothAdapter.updata(boudDeviceList)
                }
            }
        })
    }

    //初始化读卡器
    fun initReadCard() {
        if (!isConn) {
            loadingDialog.dismiss()
            return
        }
        if (api.Authenticate(500) == 1) {
            loadingDialog.dismiss()
            icInfor = IDCardInfo()
            readCard = api.Read_Card(icInfor, 2000)
            if (readCard == 1) {
                Toast.makeText(this, "读取成功", Toast.LENGTH_SHORT).show()
                //获取身份数据
                //获取身份数据
                when (icInfor.getcertType()) {
                    " " -> {
                        arrivePeopleInfor.id = icInfor.idCard
                        arrivePeopleInfor.name = icInfor.peopleName
                        etUsername.text =
                            Editable.Factory.getInstance().newEditable(icInfor.peopleName)
                        etUsernum.text = Editable.Factory.getInstance().newEditable(icInfor.idCard)
                    }

                    "J" -> {
                        arrivePeopleInfor.id = icInfor.idCard
                        arrivePeopleInfor.name = icInfor.peopleName
                        etUsername.text =
                            Editable.Factory.getInstance().newEditable(icInfor.peopleName)
                        etUsernum.text = Editable.Factory.getInstance().newEditable(icInfor.idCard)

                    }
                    "I" -> {
                        arrivePeopleInfor.id = icInfor.idCard
                        arrivePeopleInfor.name = icInfor.peopleName
                        etUsername.text =
                            Editable.Factory.getInstance().newEditable(icInfor.peopleName)
                        etUsernum.text = Editable.Factory.getInstance().newEditable(icInfor.idCard)
                    }
                }
            }
        }
    }

    fun initArriveAddressDialog() {
        view = View.inflate(this, R.layout.dialog_arrive_address, null)
        var build: AlertDialog.Builder = AlertDialog.Builder(this)
        build.setView(view)
        chooseAddressDialog = build.create()

        rvAddress = view.findViewById(R.id.rv_address)
        var grid: GridLayoutManager = GridLayoutManager(this, 2)
        rvAddress.layoutManager = grid
        arriveAddressAdapter =
            ArriveAddressAdapter(this, object : ArriveAddressAdapter.ChooseAddressCallback {
                override fun chooseAddress(arriveAddress: ArriveAddressBean?) {
                    chooseAddressDialog.dismiss()
                    arrivePeopleInfor.addressId = arriveAddress?.id.toString()
                    tvChooseArrive.text = arriveAddress?.name
                }

            })
        rvAddress.adapter = arriveAddressAdapter
        presenter.getArriveAddress()
    }

    fun initExitDialog() {
        var view: View = View.inflate(this, R.layout.dialog_exit, null)
        var build: AlertDialog.Builder = AlertDialog.Builder(this)
        build.setView(view)
        exitDialog = build.create()
        exitDialog.setCanceledOnTouchOutside(true)
        tvConfirm = view.findViewById(R.id.tv_confirm)
        tvCancel = view.findViewById(R.id.tv_cancel)
        tvConfirm.setOnClickListener {
            finish()
        }
        tvCancel.setOnClickListener {
            exitDialog.dismiss()
        }
    }

    fun initConfirmInfor() {
        var view: View = View.inflate(this, R.layout.dialog_confiem_again, null)
        var build: AlertDialog.Builder = AlertDialog.Builder(this)
        build.setView(view)
        confirmDialog = build.create()

        tvConfirmConnect = view.findViewById(R.id.tv_confirm_connect)
        tvConfirmCancel = view.findViewById(R.id.tv_confirm_cancel)
        tvUsername = view.findViewById(R.id.tv_username)
        tvIdCard = view.findViewById(R.id.tv_id_card)
        tvArriveAddress = view.findViewById(R.id.tv_arrive_address)

        tvConfirmConnect.setOnClickListener {
            loadingDialog.show()
            arrivePeopleInfor.toge_number = followPeople.toString()
            if (StringUtils.isBlank(arrivePeopleInfor.name)) {
                arrivePeopleInfor.name = etUsername.text.trim().toString()
            }
            if (StringUtils.isBlank(arrivePeopleInfor.id)) {
                arrivePeopleInfor.id = etUsernum.text.trim().toString()
            }
            presenter.addArriveInfor(arrivePeopleInfor)
        }
        tvConfirmCancel.setOnClickListener {
            confirmDialog.dismiss()
        }
    }

    fun resertUI() {
        etUsernum.text = Editable.Factory.getInstance().newEditable("")
        etUsername.text = Editable.Factory.getInstance().newEditable("")
        tvChooseArrive.text = "请选择要到苏州哪个区"
        tvNoCardNum.text = "0"
        followPeople = 0
        arrivePeopleInfor.name = ""
        arrivePeopleInfor.id = ""
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_BACK -> {
                exitDialog.show()
            }
        }
        return super.onKeyDown(keyCode, event)
    }


    override fun onDestroy() {
        super.onDestroy()
        api.unInit()
    }

}